package com.example.androidautoproject.utils

import android.os.Build
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import kotlin.math.min

object NodePrinter {

    private const val MAX_DEPTH = 5 // 限制递归深度，防止堆栈溢出
    private const val MAX_CHILDREN = 20 // 限制子节点数量
    private const val MAX_TEXT_LENGTH = 100 // 限制文本长度

    fun printNodeInfo(nodes: List<AccessibilityNodeInfo>, tag: String = "NodeInfo") {
        if (nodes.isEmpty()) {
            Log.d(tag, "No nodes found")
            return
        }

        Log.d(tag, "Found ${nodes.size} nodes:")
        nodes.forEachIndexed { index, node ->
            Log.d(tag, "\n===== Node #${index + 1} =====")
            printNodeDetails(node, 0)
            Log.d(tag, "=======================")
        }
    }

    private fun printNodeDetails(node: AccessibilityNodeInfo?, depth: Int) {
        if (node == null || depth > MAX_DEPTH) return

        val indent = "  ".repeat(depth)

        try {
            // 基本属性
            Log.d("NodeInfo", "$indent- Class: ${node.className}")
            Log.d("NodeInfo", "$indent- Package: ${node.packageName}")
            Log.d("NodeInfo", "$indent- Text: ${node.text?.toString()?.take(MAX_TEXT_LENGTH)}")
            Log.d("NodeInfo", "$indent- ContentDesc: ${node.contentDescription?.toString()?.take(MAX_TEXT_LENGTH)}")
            Log.d("NodeInfo", "$indent- ViewId: ${node.viewIdResourceName}")
//            Log.d("NodeInfo", "$indent- Bounds: ${node.boundsInScreen}")

            // 状态信息
            Log.d("NodeInfo", "$indent- Checkable: ${node.isCheckable}")
            Log.d("NodeInfo", "$indent- Checked: ${node.isChecked}")
            Log.d("NodeInfo", "$indent- Clickable: ${node.isClickable}")
            Log.d("NodeInfo", "$indent- Enabled: ${node.isEnabled}")
            Log.d("NodeInfo", "$indent- Focusable: ${node.isFocusable}")
            Log.d("NodeInfo", "$indent- Focused: ${node.isFocused}")
            Log.d("NodeInfo", "$indent- LongClickable: ${node.isLongClickable}")
            Log.d("NodeInfo", "$indent- Password: ${node.isPassword}")
            Log.d("NodeInfo", "$indent- Scrollable: ${node.isScrollable}")
            Log.d("NodeInfo", "$indent- Selected: ${node.isSelected}")
            Log.d("NodeInfo", "$indent- Visible: ${node.isVisibleToUser}")

            // 操作信息
            val actions = StringBuilder()
            for (action in node.actionList) {
                actions.append(actionToString(action)).append(", ")
            }
            Log.d("NodeInfo", "$indent- Actions: ${actions.toString().removeSuffix(", ")}")

            // 额外信息
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d("NodeInfo", "$indent- HintText: ${node.hintText}")
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                Log.d("NodeInfo", "$indent- TooltipText: ${node.tooltipText}")
            }

            // 打印子节点（递归）
            val childCount = min(node.childCount, MAX_CHILDREN)
            if (childCount > 0) {
                Log.d("NodeInfo", "$indent- Children ($childCount):")
                for (i in 0 until childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        printNodeDetails(child, depth + 1)
                        child.recycle()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("NodeInfo", "Error printing node: ${e.message}")
        }
    }

    private fun actionToString(action: AccessibilityNodeInfo.AccessibilityAction): String {
        return when (action.id) {
            AccessibilityNodeInfo.ACTION_CLICK -> "CLICK"
            AccessibilityNodeInfo.ACTION_LONG_CLICK -> "LONG_CLICK"
            AccessibilityNodeInfo.ACTION_FOCUS -> "FOCUS"
            AccessibilityNodeInfo.ACTION_SCROLL_FORWARD -> "SCROLL_FORWARD"
            AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD -> "SCROLL_BACKWARD"
            AccessibilityNodeInfo.ACTION_SET_TEXT -> "SET_TEXT"
            else -> "UNKNOWN (${action.id})"
        }
    }
}